package com.epalmpay.util;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**腾讯地图类ApiHelper
 *  * Created by wzq on 2017/7/5.
 */
public class QqMapApiHelper {
    //距离计算URL
    public static final String  DISTANCE_CALCULATE_URL="http://apis.map.qq.com/ws/distance/v1/?";
    //坐标转换
    public static final String  ORDINATE_TRANSLATE_URL="http://apis.map.qq.com/ws/coord/v1/translate?";
    //逆地址调用
    public static final String  LOCATION_TRANSLATE_URL="http://apis.map.qq.com/ws/geocoder/v1/?location=";

    public static final String  MAP_KEY="JH6BZ-IWI3D-DCC44-PNWOM-4DHWV-QVBUO";
    public static final String  MODE_DRIVING="driving";
    public static final String  MODE_WALKING="walking";

    private static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    /***
     * 获得距离
     * @param mode
     * @param fromLongitude
     * @param fromLatitude
     * @param toLongitude
     * @param toLatitude
     * @return -1失败 其它成功
     */
    public static long getDistance(String mode,String fromLatitude,String fromLongitude,String toLatitude,String toLongitude) throws Exception {
        long result = -1;
        StringBuffer sb = new StringBuffer();
        String parameters = sb.append("mode=").append(mode).append("&from=").
                append(fromLatitude).append(StringUtil.COMMA_STRING_GAP).append(fromLongitude).append("&to=").
                append(toLatitude).append(StringUtil.COMMA_STRING_GAP).append(toLongitude).append("&key=").append(MAP_KEY).toString();

        try {
            String retJson = HttpClientUtil.get(DISTANCE_CALCULATE_URL + parameters);
            JSONObject jsonObj = JSONObject.parseObject(retJson);
            Object statusObject = jsonObj.get("status");
            Integer status = Integer.parseInt(String.valueOf(statusObject));
            //成功
            if (status.equals(0)) {
                JSONObject resultObject=jsonObj.getJSONObject("result");
                JSONArray elementsArray=resultObject.getJSONArray("elements");//经纬度对象
                JSONObject elementObject = elementsArray.getJSONObject(0);
                result = elementObject.getLong("distance");//distance
            } else {
                result = -1;
            }

        } catch (Exception e) {
            throw e;
        }
        return result;
    }

    

    /***
     * 获得距离
     * @param mode
     * @param fromLongitude
     * @param fromLatitude
     * @param toLongitude
     * @param toLatitude
     * @return -1失败 其它成功
     */
    public static JSONArray getDistance(String mode,String fromLatitude,String fromLongitude,ArrayList<String> toLatitude,ArrayList<String>  toLongitude) throws Exception {
        StringBuffer sb = new StringBuffer();
         sb .append("&key=").append(MAP_KEY).append("mode=").append(mode).append("&from=").
                append(fromLatitude).append(StringUtil.COMMA_STRING_GAP).append(fromLongitude).append("&to=");
          int size =toLatitude.size();
         for(int i=0;i<size;i++){
        	if(i!=0){
        		 sb.append(";");
        	}
        	 sb.append(toLatitude).append(StringUtil.COMMA_STRING_GAP).append(toLongitude);
        }
        String parameters = sb.toString();

        try {
            String retJson = HttpClientUtil.get(DISTANCE_CALCULATE_URL + parameters);
            JSONObject jsonObj = JSONObject.parseObject(retJson);
            Object statusObject = jsonObj.get("status");
            Integer status = Integer.parseInt(String.valueOf(statusObject));
            //成功
            if (status.equals(0)) {
                JSONObject resultObject=jsonObj.getJSONObject("result");
                JSONArray elementsArray=resultObject.getJSONArray("elements");//经纬度对象
               return elementsArray;
            }
        } catch (Exception e) {
            throw e;
        }
        return  null;
    }
    
    /***
     * 获得位置信息
     * @param mode
     * @param latitude
     * @param longitude
     * @return -1失败 其它成功(province,city,district)
     */
    public static Map<String, Object> getLocation(String latitude,String longitude) throws Exception {
        //long result = -1;
        StringBuffer sb = new StringBuffer();

        Map<String,Object> map = new HashMap<String,Object>();
        String province = "";
        String city = "";
        String district = "";
        String parameters = sb.append(latitude).append(StringUtil.COMMA_STRING_GAP).append(longitude).
                append("&get_poi=0").append("&key=").append(MAP_KEY).toString();

        try {
            String retJson = HttpClientUtil.get(LOCATION_TRANSLATE_URL + parameters);
            JSONObject jsonObj = JSONObject.parseObject(retJson);
            Object statusObject = jsonObj.get("status");
            Integer status = Integer.parseInt(String.valueOf(statusObject));
            //成功
            if (status.equals(0)) {
                JSONObject resultObject=jsonObj.getJSONObject("result");
                JSONObject elementObject = resultObject.getJSONObject("ad_info");
                province = elementObject.getString("province");
                city = elementObject.getString("city");
                district = elementObject.getString("district");
            } else {
                //result = -1;
            }

        } catch (Exception e) {
            throw e;
        }
        map.put("province",province);
        map.put("city",city);
        map.put("district",district);
        return map;
    }

    /***
     * 坐标转换
     * @param fromLongitude
     * @param fromLatitude
     * @param type
     * 输入的locations的坐标类型
       可选值为[1,6]之间的整数，每个数字代表的类型说明：
       1 GPS坐标
       2 sogou经纬度
       3 baidu经纬度
       4 mapbar经纬度
       5 [默认]腾讯、google、高德坐标
       6 sogou墨卡托
     * @return 0成功 返回map坐标，其它map为空(size为0) toLongitude(返回)，toLatitude(返回)
     *    qq接口返回如下：
     *    其它失败
     *    状态码，0为正常,
          310请求参数信息有误，
          311key格式错误,
          306请求有护持信息请检查字符串,
          110请求来源未被授权
     */
    public static Map<String, Object> ordinateTranslate(String fromLatitude, String fromLongitude, int type) throws Exception {

        Integer status = -1;
        StringBuffer sb = new StringBuffer();
        Map<String,Object> map = new HashMap<String,Object>();

        String parameters = sb.append("&locations=").
                append(fromLatitude).append(StringUtil.COMMA_STRING_GAP).append(fromLongitude).append("&type=").
                append(type).append("&key=").append(MAP_KEY).toString();

        try {
            String retJson = HttpClientUtil.get(ORDINATE_TRANSLATE_URL + parameters);
            JSONObject jsonObj = JSONObject.parseObject(retJson);
            Object statusObject = jsonObj.get("status");
            status = Integer.parseInt(String.valueOf(statusObject));
            //成功
            if (status.equals(0)) {
                //JSONObject resultObject=jsonObj.getJSONObject("result");
                JSONArray elementsArray=jsonObj.getJSONArray("locations");//经纬度对象
                JSONObject elementObject = elementsArray.getJSONObject(0);
                Double toLongitude = elementObject.getDouble("lng");//distance
                Double toLatitude = elementObject.getDouble("lat");//distance
                map.put("toLongitude",toLongitude.toString());
                map.put("toLatitude",toLatitude.toString());
            }

        } catch (Exception e) {
            throw e;
        }
        return map;
    }


    /// <summary>
    /// 中国正常坐标系GCJ02协议的坐标，转到 百度地图对应的 BD09 协议坐标
    /// </summary>
    /// <param name="lat">维度</param>
    /// <param name="lng">经度</param>
    public static Map<String,Object> Convert_GCJ02_To_BD09(double lat,double lng)
    {
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            double x = 0, y = 0;
            y = lat;
            x = lng;
            double z =Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
            double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
            double tolng = z * Math.cos(theta) + 0.0065;
            double tolat = z * Math.sin(theta) + 0.006;
            map.put("toLongitude",String.valueOf(String.format("%.6f", tolng)));
            map.put("toLatitude",String.valueOf(String.format("%.6f", tolat)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /// <summary>
    /// 百度地图对应的 BD09 协议坐标，转到 中国正常坐标系GCJ02协议的坐标
    /// </summary>
    /// <param name="lat">维度</param>
    /// <param name="lng">经度</param>
    public static Map<String,Object> Convert_BD09_To_GCJ02(double lat, double lng)
    {
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            double x = 0, y = 0;
            x = lng - 0.0065;
            y = lat - 0.006;
            double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
            double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
            double tolng = z * Math.cos(theta);
            double tolat = z * Math.sin(theta);
            map.put("toLongitude",String.valueOf(String.format("%.6f", tolng)));
            map.put("toLatitude",String.valueOf(String.format("%.6f", tolat)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }




    public static void main(String[] args) throws Exception {
        /*long result = getDistance(MODE_DRIVING,"39.983171","116.308479",
                "39.996060","116.353455");

        System.out.println(result);*/

        Map<String,Object> map = getLocation("39.90403","116.407526");
        System.out.println(map);

        //Map<String,Object> map = ordinateTranslate("39.983171","116.308479",3);
        //double lat = 39.983171;
        //double lng = 116.308479;
        //Map<String,Object> map = Convert_BD09_To_GCJ02(lat,lng);
        //System.out.println("toLongitude=" + map.get("toLongitude"));
        //System.out.println("toLatitude=" + map.get("toLatitude"));
        //System.out.println(type.getType());
        //int result = 1;
        //result ++;
    }
}
